
#IMPORTANT: DO NOT CHANGE ANY LINE IN getPrettyString() and writeTable() functions

# This function takes stats of a team and returns a string in the required format
def getPrettyString(record):
    string = ""
    for i in range(len(record)):
        if i == 0:
            string += '{:<23}'.format(record[i])
        else:
            string += '{:>8}'.format(record[i])
    return string

# This functions prints (and writes to the outputfile) the table in the requied format
def writeTable(table):

    outfile = open("FIFA_stats.txt",'w')
    header = ["Team", "Played", "Won", "Drawn", "Lost", "GS", "GA", "GD", "Points"]
    record = getPrettyString(header)
    outfile.write(record +"\n")
    print(record)

    for team in table:
        record = getPrettyString(team)
        print(record)
        outfile.write(record+"\n")
    outfile.close()




################################################################
# Write your code below this. At the end, call writeTable(tablename)
# where tablename is the name of your table that has been sorted
# according to the criteria.
################################################################


def extract_data():
    # 提取文件数据
    with open('matches.txt','r')as f:
        matches = f.readlines()

    return matches

def generate_structure(matches):
    '''生成所有比赛结果

    matches - extract_data() 提取的所有信息

    说明:遍历每一场比赛的信息，信息计算过后逐步更新到每个队
    [0 for i in range(8)] 分别表示 [Played, Won, Drawn,Lost,GS,GA,GD,Points]
    最后的 ranks 结构：
    {
    'South Africa': [3, 1, 1, 1, 3, 5, -2, 4],
    'Mexico': [4, 1, 1, 2, 4, 5, -1, 4],
    'Uruguay': [7, 3, 2, 2, 11, 8, 3, 11],
    'France': [3, 0, 1, 2, 1, 4, -3, 1],

    ...

    }

    '''
    ranks = {}
    # res =

    for match in matches:

        data = split_match(match)

        if data[0] not in ranks.keys():
            ranks[data[0]] = [0 for i in range(8)]
        ranks[data[0]] = caculate_match(ranks[data[0]],int(data[2]),int(data[3]))

        if data[1] not in ranks.keys():
            ranks[data[1]] = [0 for i in range(8)]
        ranks[data[1]] = caculate_match(ranks[data[1]],int(data[3]),int(data[2]))
    # print(ranks)
    return ranks

def split_match(match):
    '''分离每一行的数据

    >>>split_match('South Africa:Mexico:1:1')
    ['South Africa,Mexico,1,1']

    '''
    info = match.split(':')
    if info and len(info) == 4:
        return info
    else:
        return None

def caculate_match(list_data,home_mark,away_mark):
    '''计算比赛数据统计,在原有的基础上更新数据

    list_data - 目前某队的数据 类似 [3, 1, 1, 1, 3, 5, -2, 4] 表示 [Played, Won, Drawn,Lost,GS,GA,GD,Points]
    home_mark - 该队的进球数
    away_mark - 对手的进球数


    '''
    list_data[0] += 1

    if home_mark > away_mark:
        list_data[1] += 1
    elif home_mark == away_mark:
        list_data[2] += 1
    else:
        list_data[3] += 1

    list_data[4] += home_mark
    list_data[5] += away_mark
    list_data[6] = list_data[4] - list_data[5]
    list_data[7] = 3 * list_data[1] + list_data[2]

    return list_data

def sort_ranks(dict_ranks):
    '''使用冒泡排序从大到小整理结果,冒泡算法不懂查一下资料

    dict_ranks - generate_structure() 函数的结果
    结构 :
    {
    'South Africa': [3, 1, 1, 1, 3, 5, -2, 4],
    'Mexico': [4, 1, 1, 2, 4, 5, -1, 4],
    'Uruguay': [7, 3, 2, 2, 11, 8, 3, 11],
    'France': [3, 0, 1, 2, 1, 4, -3, 1],
    ...
    }

    说明: 先将字典转列表，然后冒泡排序
    '''
    result = list(dict_ranks.items())
    count = len(result)

    for i in range(count):
        for j in range(i+1,count):
        #  print(result[i],result[j])
            if compare2country(result[i],result[j]):
                result[i],result[j] = result[j],result[i]

    table = []
    for item in result:
        team = item[0]
        data = item[1]
        data.insert(0,team)
        table.append(data)

    return table

def compare2country(country1,country2):
    '''比较两个队的次序，如果 country1 小于 country2 返回 True

    按照题目所给的情况一层层的比较

    '''
    c1 = country1[1]
    c2 = country2[1]


    points_diff = c1[7] - c2[7]
    played_diff = c1[0] - c2[0]
    gd_diff = c1[6] - c2[6]
    gs_diff = c1[4] - c2[4]
    alpha_diff = compare_alpha(country1[0],country2[0])

    if points_diff > 0:
        return False
    elif points_diff == 0 and played_diff < 0:
        return False
    elif points_diff == 0 and played_diff == 0 and gd_diff > 0:
        return False
    elif points_diff == 0 and played_diff == 0 and gd_diff == 0 and gs_diff > 0:
        return False
    elif points_diff == 0 and played_diff == 0 and gd_diff == 0 and gs_diff == 0 and alpha_diff :
        return False
    else:
        return True


def compare_alpha(country1,country2):
    '''按字母比较两个队的大小

    '''
    if len(country1) > len(country2):
        count = len(country2)
    else:
        count = len(country1)

    for i in range(count):
        alpha1 = country1[i].upper()
        alpha2 = country2[i].upper()

        if ord(alpha1) < ord(alpha2):
            return True
        elif ord(alpha1) > ord(alpha2):
            return False

    if len(country1) > len(country2):
        return False
    else:
        return True

'''弃用
def save(result):
    with open('result.txt','w')as f:
        f.write('{0:<20}\t{1:^10}\t{2:^10}\t{3:^10}\t{4:^10}\t{5:^10}\t{6:^10}\t{7:^10}\t{8:^10}'.format(
        'Team','Played','Won','Drawn','Lost','GS','GA','GD','Points'))
        f.write('\n')
        for team in result:
            f.write('{0:<20}\t{1:^10}\t{2:^10}\t{3:^10}\t{4:^10}\t{5:^10}\t{6:^10}\t{7:^10}\t{8:^10}'.format(
                team[0],team[1][0],team[1][1],team[1][2],team[1][3],team[1][4],team[1][5],team[1][6],team[1][7]))
            f.write('\n')

'''

def main():
    # 提取数据
    matches = extract_data()
    # 生成所有比赛结果
    ranks = generate_structure(matches)
    # 对结果排序
    result = sort_ranks(ranks)
    # 保存
    # save(result)
    writeTable(result)


if __name__ == '__main__':
    main()
